package org.jeecg.modules.wmhb.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.wmhb.dto.req.ProductBomReqDto;
import org.jeecg.modules.wmhb.entity.WmPlan;
import org.jeecg.modules.wmhb.service.IWmPlanService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.service.IWmTaskService;
import org.jeecg.modules.wmhb.dto.res.ProductBomResDto;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 项目计划
 * @Author: jeecg-boot
 * @Date: 2025-09-28
 * @Version: V1.0
 */
@Tag(name = "项目计划")
@RestController
@RequestMapping("/wmhb/wmPlan")
@Slf4j
public class WmPlanController extends JeecgController<WmPlan, IWmPlanService> {
    @Autowired
    private IWmPlanService wmPlanService;
    @Autowired
    private IWmTaskService wmTaskService;


    /**
     * 分页列表查询
     *
     * @param wmPlan
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "项目计划-分页列表查询")
    @Operation(summary = "项目计划-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<IPage<WmPlan>> queryPageList(WmPlan wmPlan,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<WmPlan> queryWrapper = QueryGenerator.initQueryWrapper(wmPlan, req.getParameterMap());
            List<WmPlan> list = wmPlanService.queryTreeListNoPage(queryWrapper);
            IPage<WmPlan> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = wmPlan.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            wmPlan.setPid(null);
            QueryWrapper<WmPlan> queryWrapper = QueryGenerator.initQueryWrapper(wmPlan, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<WmPlan> page = new Page<WmPlan>(pageNo, pageSize);
            IPage<WmPlan> pageList = wmPlanService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 【vue3专用】加载节点的子数据
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmPlanService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     *
     * @param async
     * @param pcode
     * @return
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = wmPlanService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     *
     * @param ls
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = wmPlanService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    /**
     * 获取子数据
     *
     * @param wmPlan
     * @param req
     * @return
     */
    //@AutoLog(value = "项目计划-获取子数据")
    @Operation(summary = "项目计划-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<WmPlan>> queryPageList(WmPlan wmPlan, HttpServletRequest req) {
        QueryWrapper<WmPlan> queryWrapper = QueryGenerator.initQueryWrapper(wmPlan, req.getParameterMap());
        List<WmPlan> list = wmPlanService.list(queryWrapper);
        IPage<WmPlan> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return 返回 IPage
     * @return
     */
    //@AutoLog(value = "项目计划-批量获取子数据")
    @Operation(summary = "项目计划-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<WmPlan> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<WmPlan> list = wmPlanService.list(queryWrapper);
            IPage<WmPlan> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param wmPlan
     * @return
     */
    @AutoLog(value = "项目计划-添加")
    @Operation(summary = "项目计划-添加")
    @RequiresPermissions("wmhb:wm_plan:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmPlan wmPlan) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        wmPlan.setPlanUserId(sysUser.getId());
        wmPlanService.addWmPlan(wmPlan);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmPlan
     * @return
     */
    @AutoLog(value = "项目计划-编辑")
    @Operation(summary = "项目计划-编辑")
    @RequiresPermissions("wmhb:wm_plan:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmPlan wmPlan) {
        wmPlanService.updateWmPlan(wmPlan);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目计划-通过id删除")
    @Operation(summary = "项目计划-通过id删除")
    @RequiresPermissions("wmhb:wm_plan:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmPlanService.deleteWmPlan(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目计划-批量删除")
    @Operation(summary = "项目计划-批量删除")
    @RequiresPermissions("wmhb:wm_plan:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmPlanService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "项目计划-通过id查询")
    @Operation(summary = "项目计划-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmPlan> queryById(@RequestParam(name = "id", required = true) String id) {
        WmPlan wmPlan = wmPlanService.getById(id);
        if (wmPlan == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmPlan);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmPlan
     */
    @RequiresPermissions("wmhb:wm_plan:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmPlan wmPlan) {
        return super.exportXls(request, wmPlan, WmPlan.class, "项目计划");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_plan:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmPlan.class);
    }

    /**
     * 计划分配事业部
     *
     * @param ids
     * @param deptId
     * @param userId
     * @return
     */
    @AutoLog(value = "项目计划-计划分配事业部")
    @Operation(summary = "项目计划-计划分配事业部")
    //@RequiresPermissions("wmhb:wm_plan:assign")
    @PostMapping(value = "/assign")
    public Result<String> assign(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "deptId", required = true) String deptId, @RequestParam(name = "userId", required = true) String userId) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmPlanService.assignPlan(idList, deptId, userId);
        return Result.OK("操作成功！");
    }

    /**
     * 通过产品清单最销售单位批量一键转换
     *
     * @param ids
     * @param userId
     * @param memo
     * @return
     */
    @AutoLog(value = "项目计划-转办")
    @Operation(summary = "项目计划-转办")
    //@RequiresPermissions("wmhb:wm_plan:transfer")
    @PostMapping(value = "/transfer")
    public Result<String> transfer(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "memo", required = false) String memo) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmPlanService.transferPlan(idList, userId, memo);
        return Result.OK("操作成功！");
    }

    /**
     * 生成技术任务
     *
     * @param ids
     * @param userId
     * @return
     */
    @AutoLog(value = "项目计划-生成技术任务")
    @Operation(summary = "项目计划-生成技术任务")
    //@RequiresPermissions("wmhb:wm_plan:generateDesign")
    @PostMapping(value = "/generateDesign")
    public Result<String> generateDesign(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmPlanService.generateDesign(idList, userId);
        return Result.OK("操作成功！");
    }

    /**
     * 通过excel导入产品设计BOM数据（生成子计划）
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importDesignBom/{wmPlanId}", method = RequestMethod.POST)
    //@RequiresPermissions("wmhb:wm_plan:importDesignBom")
    @Operation(summary = "项目计划-通过excel导入产品设计BOM数据")
    @Transactional
    public Result<?> importDesignBom(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmPlanId") String wmPlanId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ProductBomReqDto> list = ExcelImportUtil.importExcel(file.getInputStream(), ProductBomReqDto.class, params);
                ProductBomResDto wmBomResultVo = wmPlanService.uploadProductBom(list, wmPlanId);
                return Result.ok(wmBomResultVo);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 技术确认
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目计划-技术确认")
    @Operation(summary = "项目计划-技术确认")
    //@RequiresPermissions("wmhb:wm_plan:confirmDesign")
    @RequestMapping(value = "/confirmDesign", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> confirmDesign(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for(String id: idList) {
            WmPlan wmPlan = wmPlanService.getById(id);
            if(!wmPlan.getPlanStatus().equals(UserConstant.PLAN_STATUS_PREPARE)){{
                throw new RuntimeException("只有草稿状态能确认");
            }}

            wmPlan.setPlanStatus(UserConstant.DESIGN_STATUS_CONFIRMED); //更新技术状态
            wmPlanService.updateById(wmPlan);
        }
        return Result.OK("操作成功");
    }

    /**
     * 生成工艺任务
     *
     * @param ids
     * @param userId
     * @return
     */
    @AutoLog(value = "项目计划-生成工艺任务")
    @Operation(summary = "项目计划-生成工艺任务")
    //@RequiresPermissions("wmhb:wm_plan:generateProcess")
    @PostMapping(value = "/generateProcess")
    public Result<String> generateProcess(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "userId", required = true) String userId) {
        List<String> idList = Arrays.asList(ids.split(","));
        wmPlanService.generateProcess(idList, userId);
        return Result.OK("操作成功！");
    }

    /**
     * 通过excel导入产品工艺BOM数据
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importProcessBom/{wmPlanId}", method = RequestMethod.POST)
    //@RequiresPermissions("wmhb:wm_plan:importProcessBom")
    @Operation(summary = "项目计划-通过excel导入产品工艺BOM数据")
    public Result<?> importProcessBom(HttpServletRequest request, HttpServletResponse response, @PathVariable("wmPlanId") String wmPlanId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ProductBomReqDto> list = ExcelImportUtil.importExcel(file.getInputStream(), ProductBomReqDto.class, params);
                ProductBomResDto wmBomResultVo = wmTaskService.uploadProcessBom(list, wmPlanId);
                return Result.ok(wmBomResultVo);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 工艺确认
     *
     * @param id
     * @param type
     * @param processAuditUserId
     * @return
     */
    @AutoLog(value = "项目计划-工艺确认")
    @Operation(summary = "项目计划-工艺确认")
    //@RequiresPermissions("wmhb:wm_plan:confirmProcess")
    @RequestMapping(value = "/confirmProcess", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> confirmProcess(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "type", required = true) String type, @RequestParam(name = "processAuditUserId", required = true) String processAuditUserId) {
        wmPlanService.confirmProcess(id, type, processAuditUserId);
        return Result.OK("操作成功");
    }

    /**
     * 工艺审核
     *
     * @param id
     * @param processStatus
     * @param remark
     * @return
     */
    @AutoLog(value = "项目计划-工艺审核")
    @Operation(summary = "项目计划-工艺审核")
    //@RequiresPermissions("wmhb:wm_plan:auditProcess")
    @RequestMapping(value = "/auditProcess", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> auditProcess(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "processStatus", required = true) String processStatus, @RequestParam(name = "remark", required = false) String remark) {
        wmPlanService.auditProcess(id, processStatus, remark);
        return Result.OK("操作成功");
    }


}
